package com.zu.commu.saveData;

import com.zu.commu.interf.Data;

import java.util.Vector;

public class DataQueue
{
  private static Vector<Data> firstQueue;
  private static Vector<Data> secondQueue;
  private static Boolean firstQueueCanRead;
  private static Boolean secondQueueCanRead;
  private static DataQueue instance;
  private static SaveDataWorker saveDataWorker;
  private Object synObj1 = new Object();

  private Object synObj2 = new Object();

  private DataQueue()
  {
    firstQueue = new Vector();
    secondQueue = new Vector();
    firstQueueCanRead = new Boolean(false);
    secondQueueCanRead = new Boolean(false);
    saveDataWorker = SaveDataWorker.instance(this);
    Object o = saveDataWorker;
    if (o != null)
      o = null;
  }

  public static DataQueue instance()
  {
    if (instance == null) {
      instance = new DataQueue();
    }
    return instance;
  }

  public void setDataToFirstQueue(Data data)
  {
    synchronized (this.synObj1) {
      firstQueue.add(data);
      firstQueueCanRead = new Boolean(true);
      this.synObj1.notifyAll();
    }
  }

  public void setDataToSecondQueue(Data data)
  {
    synchronized (this.synObj2) {
      secondQueue.add(data);
      secondQueueCanRead = new Boolean(true);
      this.synObj2.notify();
    }
  }

  public Data getDataFromFirstQueue()
    throws InterruptedException
  {
    Data d = null;
    while (true) {
      synchronized (this.synObj1) {
        if (firstQueueCanRead.booleanValue()) {
          if (firstQueue.size() > 0) {
            d = (Data)firstQueue.firstElement();
            firstQueue.remove(d);
          } else {
            firstQueueCanRead = new Boolean(false);
            this.synObj1.wait();
          }
        }
        else this.synObj1.wait();
      }

      if (d != null)
      {
        return d;
      }
    }
  }

  public Data getDataFromSecondQueue()
    throws InterruptedException
  {
    Data d = null;
    while (true) {
      synchronized (this.synObj2) {
        if (secondQueueCanRead.booleanValue()) {
          if (secondQueue.size() > 0) {
            d = (Data)secondQueue.firstElement();
            secondQueue.remove(d);
          } else {
            secondQueueCanRead = new Boolean(false);
            this.synObj2.wait();
          }
        }
        else this.synObj2.wait();
      }

      if (d != null)
      {
        return d;
      }
    }
  }
}